import { Controller, Get, Inject } from '@nestjs/common';
import { AppService } from './app.service';
import { ClientProxy } from '@nestjs/microservices';
import { catchError, Observable, timeout } from 'rxjs';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    @Inject('MATH_SERVICE') private client: ClientProxy,
  ) {}

  @Get()
  getHello(): Observable<number> {
    const pattern = { cmd: 'sum' };
    const payload = [1, 2, 3, 99];
    // 【通讯1】触发 MATH_SERVICE 服务中的定义 pattern 方法
    return this.client.send<number>(pattern, payload);
  }
  @Get('events')
  getEvents(): Observable<any> {
    return this.client
      .emit<number>('user_created', {
        userId: 1,
        name: 'John Doe',
      })
      .pipe(
        timeout(1000),
        catchError((err) => {
          console.log(err);
          return [];
        }),
      );
  }
}
